package com.ruoyi.salesman.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.recycle.constant.OrderInfoConstant;
import com.ruoyi.recycle.domain.*;
import com.ruoyi.recycle.dto.StatisticsDto;
import com.ruoyi.recycle.dto.TotalShopData;
import com.ruoyi.recycle.dto.TotalShopList;
import com.ruoyi.recycle.exception.BusinessException;
import com.ruoyi.recycle.service.*;
import com.ruoyi.recycle.utils.OrderNoGenerateUtil;
import com.ruoyi.recycle.vo.MyBill;
import com.ruoyi.recycle.vo.OneStatistics;
import com.ruoyi.recycle.vo.OneShopStatisticsVo;
import com.ruoyi.salesman.dto.ClientDetail;
import com.ruoyi.salesman.dto.PersonalInformation;
import com.ruoyi.salesman.service.HomeService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;

@Service
public class HomeServiceImpl implements HomeService {

    @Resource
    private ISalesmanManagementService salesmanManagementService;
    @Resource
    private OrderNoGenerateUtil orderNoGenerateUtil;
    @Resource
    private IIntegralConfigService integralConfigService;
    @Resource
    private IFinanceManagementService financeManagementService;
    @Resource
    private ExchangeRecordService exchangeRecordService;
    @Resource
    private BillRecordService billRecordService;
    @Resource
    private IClientUserManagementService clientUserManagementService;
    @Resource
    private IMerchantManagementService merchantManagementService;


    @Override
    public Boolean withdraw(Long salesmanId, Integer withdrawAmount) {
        final SalesmanManagement salesman = salesmanManagementService.getById(salesmanId);
        Assert.isFalse(withdrawAmount > salesman.getIntegral(), () -> new BusinessException("提现积分大于当前账户积分,请输入正确的提现积分"));
        salesmanManagementService.updateById(salesman.setIntegral(salesman.getIntegral() - withdrawAmount));
        final String withdrawOrderNo = orderNoGenerateUtil.getIncr(OrderInfoConstant.WITHDRAW_ORDER);
        final IntegralConfig config = integralConfigService.getOne(Wrappers.lambdaQuery(new IntegralConfig()).eq(IntegralConfig::getName, "积分规则"));
        final BigDecimal amount = BigDecimal.valueOf(withdrawAmount).divide(BigDecimal.valueOf(config.getIntegral()));
        financeManagementService.save(new FinanceManagement().setWithdrawIntegral(Long.valueOf(withdrawAmount))
                .setWithdrawMoney(amount)
                .setWithdrawType("微信")
                .setUserName(salesman.getSalesmanNumber())
                .setStatus("待审核")
                .setOrderNumber(withdrawOrderNo)
                .setBankName(salesman.getBankName())
                .setBankNumber(salesman.getBankNumber())
                .setBankUserName(salesman.getBankUserName()));
        exchangeRecordService.save(new ExchangeRecord().setOrderNo(withdrawOrderNo).setType("1").setSource("业务员").setAmount(amount).setAccount(salesman.getSalesmanNumber()).setExchangeStatus("待审核"));
        return true;
    }


    @Override
    public AjaxResult totalShopData(Long salesmanId, Integer type, String signTime, String shopType) {
        //需要具备的内容：平台总店数、平台总拉新、平台总订单、本月总拉新、本月总订单
        TotalShopData totalShopData = salesmanManagementService.selectTotalShopData(salesmanId);
        //列表内容：
        List<TotalShopList> totalShopList = new ArrayList<>();
        //0全部平台信息，1.今日拉新最高，2.月拉新最高，3.月订单最高，4.平台类型查询，5.签约时间查询
        if (type == 0) {
            totalShopList = salesmanManagementService.selectTotalShopList(salesmanId);
        } else if (type == 1) {
            totalShopList = salesmanManagementService.selectTotalShopListOrderByToDayNewClient(salesmanId);
        } else if (type == 2) {
            totalShopList = salesmanManagementService.selectTotalShopListOrderByMonthNewClient(salesmanId);
        } else if (type == 3) {
            totalShopList = salesmanManagementService.selectTotalShopListOrderByMonthOrder(salesmanId);
        } else if (type == 4) {
            totalShopList = salesmanManagementService.selectTotalShopListByShopType(salesmanId, shopType);
        } else if (type == 5) {
            totalShopList = salesmanManagementService.selectTotalShopListBySignTime(salesmanId, signTime);
        }
        totalShopData.setTotalShopList(totalShopList);
        return AjaxResult.success(totalShopData);
    }


    @Override
    public AjaxResult oneShopData(Long shopId, Integer type, String signTime) {

        OneShopStatisticsVo oneShopStatisticsVo = salesmanManagementService.oneShopData(shopId);
        List<OneStatistics> oneStatisticsList = new ArrayList<>();
        List<StatisticsDto> monthList = new ArrayList<>();
        List<StatisticsDto> newClientSums = new ArrayList<>();
        List<StatisticsDto> orderSums = new ArrayList<>();
        List<StatisticsDto> shopIncomes = new ArrayList<>();
        List<StatisticsDto> salesmanIncomes = new ArrayList<>();
        if (type == 0) {
            //日统计账单
            if (StringUtils.isBlank(signTime)){
                return AjaxResult.error("日统计的场景下，月份数据必须传");
            }
            //拉新日统计
            newClientSums = salesmanManagementService.newClientSumDay(shopId,signTime);
            //订单日统计
            orderSums = salesmanManagementService.orderSumDay(shopId,signTime);
            //平台提成日统计
            shopIncomes = salesmanManagementService.shopIncomeDay(shopId,signTime);
            //业务员日提成统计
            salesmanIncomes = salesmanManagementService.salesmanIncomeDay(shopId,signTime);

        } else if (type == 1) {
            //月统计账单
            //拉新月统计
            newClientSums = salesmanManagementService.newClientSum(shopId);
            //订单月统计
            orderSums = salesmanManagementService.orderSum(shopId);
            //平台提成月统计
            shopIncomes = salesmanManagementService.shopIncome(shopId);
            //业务员月提成统计
            salesmanIncomes = salesmanManagementService.salesmanIncome(shopId);
        }
        //拼接取全部的月份
        monthList.addAll(newClientSums);
        monthList.addAll(orderSums);
        monthList.addAll(shopIncomes);
        monthList.addAll(salesmanIncomes);

        ArrayList<StatisticsDto> list = monthList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(StatisticsDto::getQueryTime))), ArrayList::new));

        for (StatisticsDto statisticsDto : list) {
            OneStatistics oneStatistics = new OneStatistics();
            oneStatistics.setCreateDate(statisticsDto.getQueryTime());
            for (StatisticsDto newClientSum : newClientSums) {
                if (statisticsDto.getQueryTime().equals(newClientSum.getQueryTime())){
                    oneStatistics.setNewClientCount(newClientSum.getData());
                    break;
                }
            }
            for (StatisticsDto orderSum : orderSums) {
                if (statisticsDto.getQueryTime().equals(orderSum.getQueryTime())){
                    oneStatistics.setOrderCount(orderSum.getData());
                    break;
                }
            }
            for (StatisticsDto shopIncome : shopIncomes) {
                if (statisticsDto.getQueryTime().equals(shopIncome.getQueryTime())){
                    oneStatistics.setDividend(shopIncome.getData());
                    break;
                }
            }
            for (StatisticsDto salesmanIncome : salesmanIncomes) {
                if (statisticsDto.getQueryTime().equals(salesmanIncome.getQueryTime())){
                    oneStatistics.setSalesmanDividend(salesmanIncome.getData());
                    break;
                }
            }
            oneStatisticsList.add(oneStatistics);
        }
        oneShopStatisticsVo.setOneStatisticsList(oneStatisticsList);

        return AjaxResult.success(oneShopStatisticsVo);
    }


    @Override
    public AjaxResult withdrawDepositRecord(Long salesmanId) {
        SalesmanManagement salesmanManagement = salesmanManagementService.getById(salesmanId);
        List<FinanceManagement> financeManagements = financeManagementService.list(new LambdaQueryWrapper<FinanceManagement>().eq(FinanceManagement::getUserName, salesmanManagement.getSalesmanNumber()));
        return AjaxResult.success(financeManagements);
    }


    @Override
    public AjaxResult personalInformation(Long salesmanId) {

        PersonalInformation personalInformation = new PersonalInformation();
        SalesmanManagement salesmanManagement = salesmanManagementService.getById(salesmanId);
        personalInformation.setSalesmanName(salesmanManagement.getName());
        personalInformation.setIntegral(salesmanManagement.getIntegral());
        personalInformation.setMerchantId(salesmanManagement.getMerchantId());
        Long totalPersonalInformation = salesmanManagementService.selectTotalPersonalInformation(salesmanId);
        personalInformation.setCarbonReduction(totalPersonalInformation);
        //环保勋章
        Integer floor = (int) Math.floor(totalPersonalInformation / 1000);
        personalInformation.setMedal(floor);
        return AjaxResult.success(personalInformation);
    }


    @Override
    public AjaxResult myBill(Long salesmanId, Integer type, String signTime) {
        MyBill myBill = salesmanManagementService.myBill(salesmanId);
        List<BillRecord> billRecords;
        //0收入1支出
        if (type == 0) {
            billRecords = billRecordService.selectInSalesmanBill(signTime, salesmanId);
        } else {
            billRecords = billRecordService.selectOutSalesmanBill(signTime, salesmanId);
        }
        myBill.setBillRecords(billRecords);
        return AjaxResult.success(myBill);
    }

    @Override
    public AjaxResult clientDetail(Long clientId) {
        ClientUserManagement clientUserManagement = clientUserManagementService.getById(clientId);

        SalesmanManagement salesmanManagement = salesmanManagementService.getById(clientUserManagement.getSalesmanId());

        ClientDetail clientDetail = new ClientDetail();
        clientDetail.setClientName(clientUserManagement.getUserName());
        clientDetail.setPhone(clientUserManagement.getPhone());
        clientDetail.setCity(clientUserManagement.getCity());
        clientDetail.setSalesmanName(salesmanManagement.getName());
        MerchantManagement merchantManagement = merchantManagementService.getById(salesmanManagement.getMerchantId());
        if (ObjectUtils.isNotEmpty(merchantManagement)) {
            clientDetail.setComprehensive(merchantManagement.getMerchantName());
        }
        return AjaxResult.success(clientDetail);
    }


    @Override
    public AjaxResult totalClientData(Long salesmanId, Integer type, String signTime) {
        //需要具备的内容：达人总数、达人总拉新、达人总下单、本月总拉新、本月总订单
        TotalShopData totalShopData = salesmanManagementService.selectTotalClientData(salesmanId);
        //列表内容：
        //0全部平台信息，1.今日拉新最高，2.月拉新最高，3.月订单最高，4.签约时间查询
        List<TotalShopList> totalShopList = salesmanManagementService.selectTotalClientList(salesmanId,type,signTime);
        totalShopData.setTotalShopList(totalShopList);
        return AjaxResult.success(totalShopData);
    }

    @Override
    public AjaxResult oneClientData(Long clientId, Integer type, String signTime) {
        OneShopStatisticsVo oneShopStatisticsVo = salesmanManagementService.oneClientData(clientId);
        List<OneStatistics> oneStatisticsList = new ArrayList<>();
        List<StatisticsDto> monthList = new ArrayList<>();
        List<StatisticsDto> newClientSums = new ArrayList<>();
        List<StatisticsDto> orderSums = new ArrayList<>();
        List<StatisticsDto> shopIncomes = new ArrayList<>();
        List<StatisticsDto> salesmanIncomes = new ArrayList<>();
        if (type == 0) {
            //日统计账单
            if (StringUtils.isBlank(signTime)){
                return AjaxResult.error("日统计的场景下，月份数据必须传");
            }
            //拉新日统计
            newClientSums = salesmanManagementService.clientNewClientSumDay(clientId,signTime);
            //订单日统计
            orderSums = salesmanManagementService.clientOrderSumDay(clientId,signTime);
            //订单结算
            shopIncomes = salesmanManagementService.clientOrderIntegralSumDay(clientId,signTime);
            //业务员日提成统计
            salesmanIncomes = salesmanManagementService.clientSalesmanIncomeDay(clientId,signTime);

        } else if (type == 1) {
            //月统计账单
            //拉新月统计
            newClientSums = salesmanManagementService.clientNewClientSum(clientId);
            //订单月统计
            orderSums = salesmanManagementService.clientOrderSum(clientId);
            //订单月结算
            shopIncomes = salesmanManagementService.clientShopIncome(clientId);
            //业务员月提成统计
            salesmanIncomes = salesmanManagementService.clientSalesmanIncome(clientId);
        }
        //拼接取全部的月份
        monthList.addAll(newClientSums);
        monthList.addAll(orderSums);
        monthList.addAll(shopIncomes);
        monthList.addAll(salesmanIncomes);

        ArrayList<StatisticsDto> list = monthList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(StatisticsDto::getQueryTime))), ArrayList::new));

        for (StatisticsDto statisticsDto : list) {
            OneStatistics oneStatistics = new OneStatistics();
            oneStatistics.setCreateDate(statisticsDto.getQueryTime());
            for (StatisticsDto newClientSum : newClientSums) {
                if (statisticsDto.getQueryTime().equals(newClientSum.getQueryTime())){
                    oneStatistics.setNewClientCount(newClientSum.getData());
                    break;
                }
            }
            for (StatisticsDto orderSum : orderSums) {
                if (statisticsDto.getQueryTime().equals(orderSum.getQueryTime())){
                    oneStatistics.setOrderCount(orderSum.getData());
                    break;
                }
            }
            for (StatisticsDto shopIncome : shopIncomes) {
                if (statisticsDto.getQueryTime().equals(shopIncome.getQueryTime())){
                    oneStatistics.setDividend(shopIncome.getData());
                    break;
                }
            }
            for (StatisticsDto salesmanIncome : salesmanIncomes) {
                if (statisticsDto.getQueryTime().equals(salesmanIncome.getQueryTime())){
                    oneStatistics.setSalesmanDividend(salesmanIncome.getData());
                    break;
                }
            }
            oneStatisticsList.add(oneStatistics);
        }
        oneShopStatisticsVo.setOneStatisticsList(oneStatisticsList);

        return AjaxResult.success(oneShopStatisticsVo);
    }
}
